# -*- coding: utf-8 -*-  
__author__ = 'hftec'
import threading, time,simplejson
#import Server
import SerialComunicate
class TcpThread:

    def __init__(self,tcp):
        self.tcp = tcp
        self.tcp_data = threading.Thread(target = self.wait_data)
        self.serial_data = threading.Thread(target = self.wait_serial_data)
        self.tcp_data.start()
        self.serial_data.start()
    def wait_data(self):
        while(True):
            try:
                data = self.tcp.recv(512)
                if data == '':
                    return
                print "data",data

                try:
                    cmd_json = simplejson.loads(data)
                    data_hex="";
                    for i in range(len(cmd_json["data"])/2):
                        ch = cmd_json["data"][i*2:(i*2+2)]
                        data_hex += chr(int(ch,16))
                    print "data_hex",data_hex
                    SerialComunicate.serial.write(data_hex)
                except Exception,e:
                    print "json loads error ",e
            except:
                return



    def wait_serial_data(self):
	while True:
       		if SerialComunicate.queue.empty()== False:
            		self.tcp.send(SerialComunicate.queue.get(1))